package com.thinkcoder.annotation;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;


import java.lang.annotation.*;
import java.util.HashSet;
import java.util.Set;


import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Documented
//该注解由哪个类校验
@Constraint(validatedBy = {ListValue.ListValueConstraintValidator.class})
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface ListValue {

    String message() default "{com.thinkcoder.annotation.ListValue.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default { };

    int[] value();

    class ListValueConstraintValidator implements ConstraintValidator<ListValue,Integer> {
        private Set<Integer> set=new HashSet<>();

        //获取value属性指定的数字,存入set集合
        @Override
        public void initialize(ListValue constraintAnnotation) {
            int[] value = constraintAnnotation.value();
            for (int i : value) {
                set.add(i);
            }
        }

        //校验用户输入数据是否在set集合中
        //isValid第一个参数传入要校验属性的类型
        @Override
        public boolean isValid(Integer value, ConstraintValidatorContext context) {
            return  set.contains(value);
        }
    }
}
